<template>
  <!-- 热门招聘城市 -->
  <div class="wrapper">
    <el-row class="search-container">
      <el-form ref="form" label-width="auto"> </el-form>
    </el-row>
    <div class="chartMain">
      <template v-if="chartDataIsNotEmpty">
        <div class="h100" ref="line_echartDom"></div>
        <div class="regionLineDesc">
          <div
            class="regionLineDescItem"
            v-for="(item, index) in descList"
            :key="index"
          >
            <div class="regionLineDescItemIndex">
              {{ index + 1 >= 10 ? index + 1 : '0' + (index + 1) }}
            </div>
            <div class="regionLineDescItemName">{{ item.name }}</div>
            <div class="regionLineDescItemProgress">
              <div
                class="regionLineDescItemProgressInner"
                :style="{
                  'border-right': `${
                    ((100 - item.value) / 100) * 282
                  }px solid #e4ebf4`
                }"
              ></div>
            </div>
            <div class="regionLineDescItemValue">{{ item.value }} 热度</div>
          </div>
        </div>
      </template>
      <el-empty class="empty" description="暂无数据" v-else
        ><el-button type="primary" size="mini" @click="handleKnowClick()">
          想要了解
        </el-button></el-empty
      >
    </div>
  </div>
</template>

<script>
import { chartHotcity } from '@/api/position-detail.js';
import chinaMapData from './mapData/china';
import { reportLackDataPosition } from '@/api/salary';
export default {
  name: 'chinaMap',
  components: {},
  data() {
    return {
      resData: [],
      chartDataIsNotEmpty: true, //必须让图表先显示，不然会出现空白
      chartData: [],
      descList: [],
      selectBetweenTime: [],
      pickerMinDate: '',
      average: '',
      regionLineDescAvg: ''
    };
  },
  created() {},
  mounted() {
    this.fetchData();
    // this.init();
  },
  methods: {
    fetchData() {
      this.listLoading = true;
      const params = {
        id: this.$route.query.id
      };
      chartHotcity(params)
        .then((response) => {
          if (response.code == 200) {
            this.chartData = this.handleData(response.data);
            this.chartDataIsNotEmpty =
              response.data && response.data.length > 0;
            setTimeout(() => {
              this.init();
            }, 500);
          } else {
            this.chartDataIsNotEmpty = false;
          }
        })
        .catch(() => {
          this.chartDataIsNotEmpty = false;
        });
    },
    handleData(data) {
      // 降序
      // data.sort((a, b) => {
      //   return b.salaryNum - a.salaryNum;
      // });

      const dataArr = data.map((item, index) => {
        return {
          code: item.salaryRegionId,
          name: item.salaryRegionName.replace(/省|自治区/g, ''),
          value: item.heatNum.toFixed(2)
        };
      });
      dataArr.sort((a, b) => {
        return b.value - a.value;
      });
      this.descList = dataArr.slice(0, 9);
      return dataArr;
    },
    init() {
      if (!this.$refs['line_echartDom']) return;
      //必须先注册地图,才能在下面使用type:"china"
      this.myChart = this.$echarts.init(this.$refs['line_echartDom']);
      this.$echarts.registerMap('china', chinaMapData);
      var mapData = this.$echarts.getMap('china');
      let data = this.chartData;

      let visualMapColors = [
        '#D8D8D8',
        '#D0F3EC',
        '#40CDB1',
        '#028A6E',
        '#16483F'
      ];
      let legendData = [
        '0-20 热度',
        '20-40 热度',
        '40-60 热度',
        '60-80 热度',
        '80-100 热度'
      ];
      // 根据 legend 数据项和 visualMap 范围对数据进行分组
      let categorizedData = legendData.map((range, index) => {
        let [min, max] = range.split(' ')[0].split('-').map(Number);
        return {
          name: range,
          type: 'map',
          mapType: 'china',
          selectedMode: 'none',
          geoIndex: 0,
          roam: false, // 禁用拖动和缩放功能
          label: {
            show: false
          },
          itemStyle: {
            normal: {
              borderColor: '#FFFFFF', // 正常状态下的分割线颜色
              borderWidth: 1, // 分割线宽度
              color: visualMapColors[index]
            },
            emphasis: {
              borderColor: '#FFFFFF', // 高亮状态下的分割线颜色
              borderWidth: 2, // 分割线宽度
              areaColor: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  color: '#46EACE',
                  offset: 0
                },
                {
                  color: '#5280FF',
                  offset: 1
                }
              ]), // 高亮时的填充颜色
              color: visualMapColors[index], // 高亮时的填充颜色
              shadowBlur: 4,
              shadowColor: 'rgba(14, 123, 62, 0.4)',
              shadowOffsetX: 0,
              shadowOffsetY: 6,
              label: {
                show: false // 在高亮状态下也隐藏省份名称标签
              }
            }
          },
          zoom: 1, //当前视角的缩放比例
          data: data.filter((item) => item.value >= min && item.value < max)
        };
      });

      let option = {
        // geo: [
        //   {
        //     // 地理坐标系组件
        //     map: "china",
        //     // 这里是重点！！！
        //     regions: [
        //       {
        //         name: "南海诸岛",
        //         itemStyle: {
        //           // 隐藏地图
        //           normal: {
        //             // opacity: 0, // 为 0 时不绘制该图形
        //             borderColor: "#000",
        //             borderWidth: "4px",
        //           },
        //         },
        //         label: {
        //           show: false, // 隐藏文字
        //         },
        //       },
        //     ],
        //   },
        // ],
        title: {
          text: '',
          left: 'center'
        },
        /**
         * 你可以自定义样式
         **/
        grid: {
          top: 10,
          bottom: 0 // 为 legend 预留空间
        },
        tooltip: {
          formatter: function (params) {
            return params.name + '  ' + '热度：' + (params.value || '暂无数据');
          }
        },
        legend: {
          orient: 'horizontal',
          left: 'center',
          bottom: -5, // 调整位置以避免被覆盖
          itemWidth: 8, // 图例图标宽度
          itemHeight: 8, // 图例图标高度
          data: legendData.map((name, index) => ({
            name: name,
            icon: 'circle', // 设置图例项的图标为圆形，可选rect矩形
            itemStyle: {
              color: visualMapColors[index], // 设置图例项的颜色与 visualMap 的颜色一致
              borderColor: visualMapColors[index] // 设置边框颜色为相同颜色以去除边框
              // borderWidth: 0, // 边框宽度
            },
            textStyle: {
              color: '#BFBFBF',
              lineHeight: 12
            }
          }))
        },
        visualMap: {
          tyep: 'piecewise',
          min: 0,
          max: 100,
          left: 'right',
          top: 'bottom',
          text: ['高', '低'],
          calculable: false,
          // seriesIndex: [1],
          inRange: {
            color: visualMapColors
          },
          show: false
        },
        series: categorizedData
      };
      this.myChart.clear();
      option && this.myChart.setOption(option);
      window.addEventListener('resize', () => {
        if (this.myChart) {
          this.myChart.resize();
        }
      });
    },
    averageCitySalary(values) {
      let salary = 0;
      values.forEach((item, index) => {
        salary = salary + item;
      });

      if (values.length > 0) {
        const result = salary / values.length;
        return result.toFixed(1);
      } else {
        return '保密';
      }
    },
    handleKnowClick() {
      const userInfo = JSON.parse(localStorage.getItem('userInfo')); //OA的userInfo和SaaS登录的userInfo不一样
      const oaId = '';
      if (userInfo && userInfo.user_source_id) {
        oaId = userInfo.user_source_id;
      }
      const params = {
        positionId: this.$route.query.id,
        positionName: this.$route.query.name,
        layerId: '161',
        layerName: '热门招聘城市',
        personId: localStorage.getItem('personId') || '',
        oaId: oaId
      };
      reportLackDataPosition(params).then((response) => {
        if (response.code == 200) {
          this.$message.success('已成功提交');
        } else {
          this.$message.error(res.status_desc);
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.wrapper {
  width: 100%;
}

.chartMain {
  display: flex;
  align-items: center;
  .empty {
    margin: auto;
    ::v-deep .el-empty__image {
      width: 150px;
    }
  }
  // padding-bottom: 15px;
}
.regionLineChart {
  display: flex;
  align-items: center;
}
.regionLineDesc {
  flex: 0.5;
  display: flex;
  flex-direction: column;
  // width: 400px;
  justify-content: left;
  align-content: center;
  margin: 10px 4px 0 54px;
}

.regionLineDescItem {
  display: flex;
  margin: 10px 0px;
  justify-content: flex-end;
  align-items: center;
  // width: 45%;
  .regionLineDescItemIndex {
    // width: 15px;
    font-family: D-DIN-PRO-600-SemiBold;
    font-family: D-DIN-PRO, D-DIN-PRO;
    font-weight: 600;
    font-size: 18px;
    color: #c3c3c3;
    line-height: 14px;
    text-align: center;
    font-style: normal;
    margin-right: 13px;
  }
  &:nth-of-type(1) .regionLineDescItemIndex {
    color: #ff643e;
  }
  &:nth-of-type(2) .regionLineDescItemIndex {
    color: #ffaa48;
  }
  &:nth-of-type(3) .regionLineDescItemIndex {
    color: #f0d22f;
  }
  .regionLineDescItemName {
    min-width: 32px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 16px;
    color: #555555;
    line-height: 14px;
    text-align: left;
    font-style: normal;
    margin-right: 18px;
  }
  .regionLineDescItemProgress {
    min-width: 282px;
    max-width: 302px;
    flex: 1;
    height: 6px;
    background: linear-gradient(243deg, #8cbaff 0%, #40cdb1 100%);
    border-radius: 3px;
    margin-right: 24px;
    .regionLineDescItemProgressInner {
      width: 100%;
      height: 6px;
      border-radius: 3px;
    }
  }
  .regionLineDescItemValue {
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 16px;
    color: #8193b2;
    line-height: 14px;
    text-align: left;
    font-style: normal;
  }
}
.h100 {
  flex: 0.5;
  min-width: 343px;
  min-height: 341px;
}
::v-deep .el-date-editor {
  background: #fafcfe;
  border-radius: 4px;
  border: 1px solid #e4edf8;
}
::v-deep .el-form-item__label {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  line-height: 22px;

  display: flex;
  align-items: center;
  justify-content: center;
  height: 27px;
  min-width: 82px !important;
}
::v-deep .el-form-item {
  margin-bottom: 6px;
}
::v-deep .el-form-item:last-of-type {
  margin-bottom: 0px;
}
::v-deep .el-form-item__label-wrap {
  margin-left: 0px !important;
}
.search-container {
  display: flex;
  align-items: center;
}
</style>
